#include "stdio.h"
#include "unistd.h"
#include "mediactrl.h"
#include "string.h"

#define AW_WIDTH 1280
#define AW_HEIGH 720
#define AW_FPS 18
#define AW_BITRATE 2*1024*1024  //2Mbps

#define DUMP_H264 //开启h264文件存储
#define RTSP      //开启rtsp网传


#ifdef DUMP_H264
FILE *h264_fp;
#endif

#ifdef RTSP
VID_RTSP_HANDLE aw_rtsp_handle;
#endif


uint64_t get_time(){

    struct timeval tv;
    gettimeofday( &tv, NULL );
    return tv.tv_sec*1000+tv.tv_usec/1000;
}

int32_t get_fps(){
    static uint64_t first_time = 0,last_time = 0;
    static int32_t cnt = 0;
    first_time = get_time();
    cnt++;
    if( first_time - last_time > 1000){
        printf( "fps = %d\r\n", cnt );
        cnt = 0;
        last_time = first_time;
    }
    return 0;
}

int32_t encCallback( VidEncOutputBuf *venc_out_buf, void *ctx ){
    if( venc_out_buf->key_flag == 1 ){

#ifdef RTSP
        VidPacket vid_pkg;
        memmove(vid_pkg.buffer, venc_out_buf->spspps_data, venc_out_buf->spspps_data_size);
        vid_pkg.is_new_frame = true;
        vid_pkg.is_IFrame = false;
        vid_pkg.size = venc_out_buf->spspps_data_size;
        vid_rtsp_deliver( aw_rtsp_handle, &vid_pkg );
#endif

#ifdef  DUMP_H264
        fwrite(venc_out_buf->spspps_data, venc_out_buf->spspps_data_size, 1, h264_fp);
#endif

    }

#ifdef RTSP
    VidPacket vid_pkg;
    memmove(vid_pkg.buffer, venc_out_buf->data, venc_out_buf->data_size);
    vid_pkg.is_new_frame = true;
    vid_pkg.is_IFrame = false;
    vid_pkg.size = venc_out_buf->data_size;
    vid_rtsp_deliver( aw_rtsp_handle, &vid_pkg );
#endif

#ifdef  DUMP_H264
    fwrite(venc_out_buf->data, venc_out_buf->data_size, 1, h264_fp);
#endif

    return 0;
}

int main(){

    int32_t ret = 0;

#ifdef  DUMP_H264
    h264_fp = fopen( "/mnt/UDISK/test.h264", "w+" );
#endif

#ifdef RTSP
    RtspConfig rtsp_config = {
        .port = 554,
        .url_str = "v831_rtsp",
        .username = "fs",
        .password = "1234"
    };

    vid_rtsp_init( &rtsp_config, &aw_rtsp_handle );
    vid_rtsp_start( aw_rtsp_handle );
#endif

    aw_mediactrl_init( AW_WIDTH, AW_HEIGH, AW_FPS, AW_BITRATE );
    aw_mediactrl_regcb( encCallback, NULL );
    aw_mediactrl_start();

    while(1){

    }

    aw_mediactrl_stop();
    aw_mediactrl_deinit();

#ifdef RTSP
    vid_rtsp_stop( aw_rtsp_handle );
    vid_rtsp_deinit(aw_rtsp_handle);
#endif

#ifdef  DUMP_H264
    fclose(h264_fp);
#endif

    return 0;
}